package com.example.controller;

import com.example.service.QAService;
import com.example.service.QuestionHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/qa")
@Api(tags = "智能问答接口", description = "基于知识图谱的智能问答系统")
public class QaController {

    @Resource
    private QAService tripleQAService;

    @Resource
    private QuestionHistoryService historyService;

    /**
     * 智能问答接口
     */
    @GetMapping("/answer")
    @ApiOperation(value = "获取问题答案", notes = "输入问题，返回基于知识图谱的答案")
    public ResponseEntity<Map<String, Object>> getAnswer(
            @ApiParam(value = "用户问题", required = true, example = "秦始皇建立了什么？")
            @RequestParam("question") String question) {
        Map<String, Object> result = new HashMap<>();
        try {
            String answer = tripleQAService.answerQuestion(question);

            // 2. 新增：保存历史记录（用户ID默认temp，有登录功能时替换为真实用户ID）
            historyService.addHistory(question, answer, "temp");

            result.put("success", true);
            result.put("question", question);
            result.put("answer", answer);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "问答处理失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
